package com.sugar.psych.assessment.module.business.service.usermedal;

import com.sugar.psych.assessment.module.business.dal.dataobject.medal.MedalDO;
import com.sugar.psych.assessment.module.business.dal.mysql.medal.MedalMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import com.sugar.psych.assessment.module.business.controller.admin.usermedal.vo.*;
import com.sugar.psych.assessment.module.business.dal.dataobject.usermedal.UserMedalDO;
import com.sugar.psych.assessment.framework.common.pojo.PageResult;
import com.sugar.psych.assessment.framework.common.util.object.BeanUtils;

import com.sugar.psych.assessment.module.business.dal.mysql.usermedal.UserMedalMapper;

/**
 * 用户获得勋章信息 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class UserMedalServiceImpl implements UserMedalService {

    @Resource
    private UserMedalMapper userMedalMapper;
    @Resource
    private MedalMapper medalMapper;

    @Override
    public Long createUserMedal(UserMedalSaveReqVO createReqVO) {
        // 插入
        UserMedalDO userMedal = BeanUtils.toBean(createReqVO, UserMedalDO.class);
        userMedalMapper.insert(userMedal);
        // 返回
        return userMedal.getId();
    }

    @Override
    public void updateUserMedal(UserMedalSaveReqVO updateReqVO) {
        // 更新
        UserMedalDO updateObj = BeanUtils.toBean(updateReqVO, UserMedalDO.class);
        userMedalMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserMedal(Long id) {
        // 删除
        userMedalMapper.deleteById(id);
    }

    @Override
    public void deleteUserMedalListByIds(List<Long> ids) {
        // 删除
        userMedalMapper.deleteByIds(ids);
    }

    @Override
    public UserMedalDO getUserMedal(Long id) {
        return userMedalMapper.selectById(id);
    }

    @Override
    public PageResult<UserMedalDO> getUserMedalPage(UserMedalPageReqVO pageReqVO) {
        return userMedalMapper.selectPage(pageReqVO);
    }

    @Override
    public List<UserMedalRespVO> getUserAllGetMedal(Long userId) {
        List<MedalDO> medals = medalMapper.selectList();
        List<UserMedalDO> userMedals = userMedalMapper.selectList(UserMedalDO::getUserId, userId);
        List<UserMedalRespVO> respList = new ArrayList<>();

        for (MedalDO medal : medals) {
            UserMedalRespVO respVO = new UserMedalRespVO();
            respVO.setId(medal.getId());
            respVO.setActivated(medal.getActivated());
            respVO.setNoActivated(medal.getNoActivated());
            respVO.setIsActivated(userMedals.stream().anyMatch(u -> u.getMedalId().equals(medal.getId())));
            respList.add(respVO);
        }

        return respList;
    }
}